package com.surfilter.platform.base.servlet;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.surfilter.platform.base.service.SpringContextUtil;
import com.surfilter.platform.base.util.FileUploadUtil;
import com.surfilter.platform.base.util.PropertyHolder;

public class ImgUploadServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}
	


	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String type = req.getParameter("type");
		String nowPath = req.getSession().getServletContext().getRealPath("/"); 
		FileUploadUtil util = FileUploadUtil.getInstance();
		if("user".equals(type)){
			util.init(nowPath + com.surfilter.platform.base.model.Constants.IMG_PERSON_PATH,nowPath + com.surfilter.platform.base.model.Constants.IMG_PATH);
		}else if("pos".equals(type)){
			util.init(nowPath + com.surfilter.platform.base.model.Constants.IMG_POS_PATH,nowPath + com.surfilter.platform.base.model.Constants.IMG_PATH);
		}else{
			util.init(nowPath + com.surfilter.platform.base.model.Constants.IMG_COM_PATH,nowPath + com.surfilter.platform.base.model.Constants.IMG_PATH);
		}
		BufferedOutputStream bos =  new BufferedOutputStream(resp.getOutputStream());
		resp.setHeader(   "Content-Type"   ,   "text/html;charset=utf-8" );
	        try {
				List<FileItem>  items = util.getServletFileUploadObject().parseRequest(req);
				if(items !=null && items.size() > 0){
					String result = "";
					FileItem item = items.get(0);
					String ext = item.getName().substring(item.getName().lastIndexOf(".")+1);
					if("jpg".equals(ext)||"png".equals(ext)||"jpeg".equals(ext)||"gif".equals(ext)){
						String fileName = System.currentTimeMillis()+"."+ext;
						util.saveFile(item, fileName);
						result = "{success:'true',result:'"+ fileName+"'}";
					}else{
						result = "{success:'false',msg:'错误的文件类型!'}";
					}
					bos.write(result.getBytes());
					bos.flush();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				bos.close();
				
			}
		
	}
	
}
